import React, {Component} from 'react'
import { routerShape } from 'react-router';
import {inject, observer} from 'mobx-react';
import {observable,action,toJS} from 'mobx';
import { message,Button } from 'antd';
import '../../../../style/myComment/rightContainer/weibo.less'
import { WeaRichText,WeaInput,WeaTools } from 'ecCom'
import "./CommentEdit.less"
import * as Util from '../../../../util/index'
import Dict from '../wea-comment-dict';
import { WeaLocaleProvider } from "ecCom";

var Base64 = ecCom.WeaTools.Base64;
const getLabel = WeaLocaleProvider.getLabel;

const mirror = Dict.bottomBarMirror;
@inject('checkMatterStore')
@observer

class CommentEdit extends Component {
    static contextTypes = {
        router: routerShape
    }

    constructor(props) {
        super(props)
        this.state = {
            editing: false,
            authRange: [],
            mood: "1",
            status: '',
            richValue: '',
            inputOnbulr: false,
            commenting: false
        }
        this.CKE_ID = `wea_ckeditor_weibo_edit`
        this.onTempletChange = this.onTempletChange.bind(this);
    }
    componentWillReceiveProps(nextProps){
    	const { defaultTemplate } = this.props;
    	if(!nextProps.hasSubmited && defaultTemplate && defaultTemplate.tempContent && nextProps.defaultTemplate && nextProps.defaultTemplate.tempContent && defaultTemplate.tempContent !==  nextProps.defaultTemplate.tempContent){
    		this.setState({richValue: nextProps.defaultTemplate.tempContent});
    	}
    }

    render() {
        let {saveWeaRichTextValue,taskId} =this.props.checkMatterStore
        let WeaRichTextStoreValue={}, richInit=false;
        if(this.props.checkMatterStore.status){
             WeaRichTextStoreValue = toJS(this.props.checkMatterStore.status.WeaRichTextStoreValue)
        }else{

        }
        let {editing, authRange, status, richValue,inputOnbulr,commenting} = this.state,
            {hasSubmited, defaultTemplate, weiboCKEditorConfig} = this.props;
        //暂时接入过来 zxt
        let bottomBarConfig = [];
        let uploadUrl = '';
        weiboCKEditorConfig && weiboCKEditorConfig.map(cg => {
        	cg.name === 'dialogs' && cg.items.map(item => {
        		let obj = {
	        		isBlog: true,
	        		name: 'Browser',
	        		show: <div className="wea-cb-item">
	                    <span className={`wea-cbi-icon ${mirror[item].icon}`}/>
	                    <span className="wea-cbi-text">{mirror[item].nameFunc()}</span>
	                </div>,
	        		type: mirror[item].type,
	        		title: mirror[item].nameFunc(),
	        		isSingle: item === 'Templet',
	        	};
	        	if(item === 'Templet') obj.onToolsChange = this.onTempletChange
	        	bottomBarConfig.push(obj);
	        })
        	cg.name === 'uploads' && cg.items.map(item => {
	        	bottomBarConfig.push({
	        		isBlog: true,
	        		name: 'Upload',
	        		show: <div className="wea-cb-item">
	        	        <span className='wea-cbi-icon icon-blog-Enclosure'/>
	        	        <span className="wea-cbi-text">{getLabel(387321,"附件")}</span>
	        	    </div>,
	        		uploadId: 'webo_edit',
	        		uploadUrl: `${item.Attachment.uploadUrl}?category=${item.Attachment.position}`,
	        		category: item.Attachment.position,
	        		maxUploadSize: item.Attachment.maxSize,
	        		style: {display: "inline-block"}
	        	})
	        	uploadUrl = `${item.Attachment.uploadUrl}?category=${item.Attachment.position}`;
            })
        })
        let bottomBarRight = undefined;
        if (status === 'ready') {
          bottomBarRight = {
	          width: 85,
            Component: (
        				<span className="g-rich-text-toolbar-bottom-item" style={{position: "relative"}}>
        					<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@v15t7w`} className="g-button-release" onClick={this.publishWeibo.bind(this)}>
        						<span><span className="icon-coms-Release" /><span>{getLabel(131302,"发布")}</span></span>
        					</Button>
        				</span>
            )
          };
        }
        let WeaRichTextValue = '';
        if(WeaRichTextStoreValue[`wea_rich_text_ls_${this.CKE_ID}`]=='' || WeaRichTextStoreValue[`wea_rich_text_ls_${this.CKE_ID}`] == undefined){//没有未发布的审批意见内容
            if(!hasSubmited &&  defaultTemplate && defaultTemplate.tempContent){//当天是否提交过，否;是不是初始化
                WeaRichTextValue = defaultTemplate.tempContent
            }else{//当天已经提交过
            }
        }else{//有未发布的审批意见内容
            WeaRichTextValue = WeaRichTextStoreValue[`wea_rich_text_ls_${this.CKE_ID}`]

        }

        return (
            <div className='g-ckeditor-import-ecCom  g-edit-area'>
                {
                    (<WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@bqjjbu`}
                        id={this.CKE_ID}
                        ref={this.CKE_ID}
                        ls={false}
                        value={`${WeaRichTextValue}`}
                        ckConfig={{
                            toolbar:[
                                { name: 'document', items: [ 'Source'] },
                                { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
                                { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
                                { name: 'colors', items: [ 'TextColor' ] },
                                { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
                                { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] },
                                // { name: 'tools', items: ['Maximize'] }
                            ],
                            extraPlugins: 'autogrow',
                            height:150,
                            autoGrow_minHeight: 150,
                            autoGrow_maxHeight: 600,
                            removePlugins: 'resize',
                            uploadUrl: '/api/blog/fileupload/uploadimage',
                        }}
                        bottomBarConfig={ bottomBarConfig }
                        bottomBarRight={bottomBarRight}
                        bootomBarStyle={{}}
                        onBlur = {this.richTextChange.bind(this)}
                        onStatusChange={s => this.setState({status: s})}
                        onToolsChange={Util.transfStr}
                    />)
                }

            </div>

        )
    }
    richTextChange(){
        let {saveWeaRichTextValue} =this.props.checkMatterStore;
        this.setState({richValue: this.refs[this.CKE_ID].getData()});
        saveWeaRichTextValue && saveWeaRichTextValue({[`wea_rich_text_ls_${this.CKE_ID}`]:this.refs[this.CKE_ID].getData()}, false)
    }

    onTempletChange(name, ids, list, type){
        let {saveWeaRichTextValue} =this.props.checkMatterStore

    	let { richValue } = this.state;
    	Util.templetChange(richValue,v => {this.setState({richValue: v});saveWeaRichTextValue && saveWeaRichTextValue({[`wea_rich_text_ls_${this.CKE_ID}`]:v}, false)}, name, ids, list, type)
    }
    onAuthRange = (authRange) => {
        this.setState({authRange: authRange})
    }
    addComment = () => {
      let {getInstype} =this.props.checkMatterStore;
      getInstype("1");
        this.setState({commenting: true})
    }
    publishWeibo = () => {
        this.addComment();
        let {editWeibo,instype,taskId,pagesize,pageindex} =this.props.checkMatterStore
        let {authRange, mood, richValue} = this.state,
            { user} = this.props;
        let ckref = this.refs[this.CKE_ID];
        if(this.refs[this.CKE_ID].wrappedInstance){
            ckref = this.refs[this.CKE_ID].wrappedInstance;
        }
        if (!ckref.checkMode()) {
            message.error(getLabel('384536',"不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式"));
            return;
        }
        localStorage.removeItem(`wea_rich_text_ls_${this.CKE_ID}`);
        editWeibo(
            {
                instype: instype || "1",
                taskId: taskId,
                content: this.refs[this.CKE_ID].getData(),
            },
            {
              "taskId":taskId,
              "pageindex":pageindex,
              "pagesize":pagesize
            },
            result => {
              if (result.status == "1") {
                if (this.refs[this.CKE_ID] && this.refs[this.CKE_ID].wrappedInstance) {
                  this.refs[this.CKE_ID].wrappedInstance.setData('');
                } else {
                  this.refs[this.CKE_ID].setData('');
                }
              }
            }
        );
        this.setState({commenting: false})
    }

    onReady = () => {
        this.setState({editing: true, richValue: ''})
    }
}

export default CommentEdit
